/**
* @desc:  人员管理
* @author qiankui
* @date 2023-4-15 15:38:06
*/
<template>
    <div class="page-container h-100 container">
        <!--<button @click="toTree">go</button>-->
        <div class="h-100 leftNav" element-loading-background="rgba(255, 255, 255, 0.8)" v-loading="leftTreeLoading">
            <el-card shadow="never" class="box-card">
                <!--组织-->
                <span>{{this.i18n.t('organization')}}</span>
                <div class="treeTopIcon" style="float: right;">
                    <!--收起全部(未实现)-->
                    <!--<i title="收起全部" disabled @click="packAll" style="font-size: 20px" class="iconfont-KUI icon-moduanshouqi_o"></i>-->
                    <!--刷新-->
                    <i :title="$t('Refresh')" disabled @click="refreshTree" class="el-icon-refresh"></i>
                    <!--添加组织-->
                    <i :title="$t('Add organization')" disabled @click="addOrg({})" class="el-icon-plus"></i>
                </div>
            </el-card>
            <div id="leftTreeView" style="height: calc(100% - 65px);background: #fff;overflow-y: scroll">
                <vl-tree id="customTree" ref="orgTree" class="orgTree"
                         :height="leftTreeHeight"
                         v-if="leftTreeDisplay"
                         :props="deprops" :data="noDepartmentPersonnel" >
                    <div class="custom-tree-node" slot-scope="{ node, data }">
                        <span>
                          <i v-if="data.sex==undefined" class="orgIcon iconfont-KUI icon-modules"></i>
                          <i v-if="data.sex!==undefined" :class="{'female':data.sex==1}"
                             class="el-icon-user-solid userIcon" style="margin-right:5px">
                          </i>
                          <span :title="node.label" class="noDepartmentName">{{ node.label }}</span>
                            <!--<el-tag type="info" size="mini" v-if="data.sex==undefined">{{data.children.length}}</el-tag>-->
                        </span>
                        <span>
                            <el-tag style="margin-right: 3px" type="info" size="mini" v-if="data.sex==undefined">{{getOrgPersionCount(data.children)}}</el-tag>
                                <!--<span v-if="data.sex==undefined">({{data.children.length}})</span>-->
                                <!--修改组织名称-->
                            <i @click="handleTreePersonEdit(node,data)"
                               v-if="data.id!=-100"
                               class="el-icon-edit-outline treeToolIcon orgInfoTool" :title="$t('edit')"></i>
                                <!--<i v-if="data.sex==undefined" @click="addOrg('add', node, data)" class="el-icon-plus" title="添加"></i>-->
                                <!--删除-->
<!--                            <i v-if="data.sex!=undefined" @click="deletePersonnel(data)" class="el-icon-delete treeToolIcon orgInfoTool" :title="$t('delete')"></i>-->

                            <!--删除-->
                            <i v-if="data.id!=-100" @click="remove(node, data)" class="el-icon-delete treeToolIcon" :title="$t('delete')"></i>
                        </span>

                    </div>
                </vl-tree>
            </div>
        </div>
        <div class="h-100 rightTable">
            <div class="wrapperform m-b-16">
                <div class="searchbox">
                    <el-form :inline="true" :model="form" class="demo-form-inline" :rules="rules" ref="ruleForm">
                      <el-form-item id="queryType" :label="$t('Query type')">
                        <el-input placeholder="" ref="fhx" v-model="queryText" class="input-with-select">
                          <el-select  slot="prepend" v-model="searchType" @change="searchTypeChange"
                                      :placeholder="$t('Please select a query type')">
                            <!--全部-->
                            <el-option :label="$t('All')" :value="-1"></el-option>
                            <!--姓名-->
                            <el-option :label="$t('name')" :value="0"></el-option>
                            <!--<el-option label="人员编号" :value="1"></el-option>-->
                            <!--证件号-->
                            <el-option :label="$t('Document number')" :value="2"></el-option>
                            <!--编号(工号)-->
                            <el-option :label="$t('Number (job number)')" :value="3"></el-option>
                          </el-select>

                        </el-input>
                      </el-form-item>
                      <!--登记日期-->
                      <el-form-item :label="$t('Registration Date')">
                        <el-date-picker
                            class="inputEl"
                            v-model="regDate"
                            type="daterange"
                            align="right"
                            unlink-panels
                            format="yyyy-MM-dd"
                            range-separator="~"
                            :start-placeholder="$t('Start Date')"
                            :end-placeholder="$t('End Date')"
                            :picker-options="pickerOptions">
                        </el-date-picker>
                      </el-form-item>
                      <el-form-item class="BlankPlaceholder formOperationButtons" label=".">
                        <!--查询-->
                        <el-button size="small" type="primary" class="topBtn" @click="onSearch">{{this.i18n.t('Query')}}</el-button>
                        <!--重置-->
                        <el-button size="small" type="handle" class="topBtn" @click="resetSearch">
                          {{this.i18n.t('Reset')}}
                        </el-button>
                      </el-form-item>
                    </el-form>
                </div>
            </div>
            <div class="table-container table-box globalDiv">

                <el-table
                    :scroll-x="true"
                        stripe
                        @selection-change="handleTableSelectionChange"
                        :data="listData"
                        height="calc(100vh - 295px)"
                        style="width: 100%">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            type="index"
                            label=""
                            width="50"
                            >
                        <template slot-scope="scope">
                            <span>{{(form.pageNumber - 1) * form.pageSize + scope.$index + 1}}</span>
                        </template>
                    </el-table-column>
<!--                  照片-->
                    <el-table-column
                            prop="date"
                            :label="$t('Image')"
                            width="100">
                        <template slot-scope="scope">
                            <p v-if="!('face' in scope.row.biodataInfos) || !scope.row.biodataInfos.face.length">-</p>
                            <el-image
                                    v-if="('face' in scope.row.biodataInfos) && scope.row.biodataInfos.face.length"
                                    style="width: 40px;height: 40px;"
                                    :src="scope.row.biodataInfos.face[0].showBase64Pic"
                                    fit="contain"></el-image>
                        </template>
                    </el-table-column>
<!--                  姓名-->
                    <el-table-column
                            show-overflow-tooltip
                            prop="name"
                            :label="$t('name')">
                    </el-table-column>
                  <!--                  编号-->
                    <el-table-column
                            show-overflow-tooltip
                            prop="jobNumber"
                            width="180"
                            :label="$t('Number (job number)')">
                    </el-table-column>
<!--                  性别-->
                    <el-table-column
                            prop="sex"
                            :label="$t('Gender')"
                            width="">
                        <template slot-scope="scope">
                          {{$t(sexListArr[scope.row.sex].label)}}
                        </template>
                    </el-table-column>
<!--                  手机号-->
                    <el-table-column
                            prop="telephone"
                            :label="$t('Mobile phone number')"
                            width="200">
                        <template slot-scope="scope">
                           {{scope.row.telephone===''||scope.row.telephone===null?'-':scope.row.telephone}}
                        </template>
                    </el-table-column>
<!--                  证件号码-->
                    <el-table-column
                            prop="idCard"
                            :label="$t('Document number')"
                            show-overflow-tooltip
                            width="180">
                        <template slot-scope="scope">
                            {{scope.row.idCard===''||scope.row.idCard===null?'-':scope.row.idCard}}
                        </template>
                    </el-table-column>
<!--                  组织-->
                    <el-table-column
                            prop="departmentName"
                            :label="$t('organization')"
                            show-overflow-tooltip
                            width="150">
                        <template slot-scope="scope">
                            {{scope.row.departmentName===''?'-':scope.row.departmentName}}
                        </template>
                    </el-table-column>
<!--                  考勤组-->
                    <el-table-column
                            show-overflow-tooltip
                            prop="attendanceGroup"
                            :label="$t('Attendance group')"
                            width="150">
                        <template slot-scope="scope">
                            {{ scope.row.attendanceGroup === null ? '-' : scope.row.attendanceGroup.name }}
                        </template>
                    </el-table-column>
<!--                  登记时间-->
                    <el-table-column
                            show-overflow-tooltip
                            prop="registrationTime"
                            :label="$t('Registration time')"
                            width="150">
                    </el-table-column>
<!--                  操作-->
                    <el-table-column width="150" :label="$t('operation')">
                        <template slot-scope="scope">
                            <i style="margin-right: 10px" @click="handelDetail(scope.row)" class="global-icon icon iconfont icon-eye tabIconClass"></i>
                            <i style="margin-right: 10px" @click="handlePersonEdit(scope.row)" class="global-icon icon iconfont icon-pencil-line tabIconClass"></i>
                            <i @click="deletePersonnel(scope.row)" class="global-icon icon iconfont icon-trash tabIconClass"></i>

                            <!--<el-button-->
                                    <!--size="mini"-->
                                    <!--@click="handlePersonEdit(scope.row)">编辑</el-button>-->
                            <!--<el-button-->
                                    <!--size="mini"-->
                                    <!--type="danger"-->
                                    <!--@click="delTableData(scope.row)">删除</el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!--<div class="paginationBox" style="margin-top: 10px;margin-bottom: 13px">-->
                <!---->
            <!--</div>-->

            <div style="background: #fff;padding: 10px;">
                <!--添加-->
                <el-button size="mini" @click="addTableData" icon="iconfont-KUI icon-plus-circle tableBottomToolIcon">{{this.i18n.t('Add')}}</el-button>
                <!--同步名单-->
                <el-button size="mini" @click="synchronous" icon="iconfont-KUI icon-tongbu tableBottomToolIcon">{{this.i18n.t('Synchronization list')}}</el-button>
                <!--下发名单-->
                <el-button :disabled="orginfoLoading" size="mini" @click="distributeList" icon="iconfont-KUI icon-gongdanxiafa tableBottomToolIcon">{{this.i18n.t('Send list')}}</el-button>
                <el-dropdown style="margin-left: 10px" @command="handleBottomCommand" v-loading="importLoading" >
                    <span class="el-dropdown-link">
                         <el-button size="mini" icon="el-icon-s-operation"></el-button>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                        <!--导入-->
                        <el-dropdown-item icon="el-icon-download" command="import">{{this.i18n.t('import')}}</el-dropdown-item>
                        <!--修改组织-->
                        <el-dropdown-item icon="el-icon-edit" command="modifyOrg">{{this.i18n.t('Modify Organization')}}</el-dropdown-item>
                        <!--批量删除-->
                        <el-dropdown-item icon="el-icon-delete" command="batchDelete" :disabled="!selectRow.length">{{this.i18n.t('Batch deletion')}}</el-dropdown-item>
                        <!--清空人员-->
                        <el-dropdown-item icon="el-icon-close" command="emptyingPersonnel">{{this.i18n.t('Emptying personnel')}}</el-dropdown-item>
                        <!--导出-->
                        <el-dropdown-item icon="el-icon-upload2" command="exportFile">{{this.i18n.t('Export')}}</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>

                <el-pagination
                        style="display: inline-block;float: right"
                        small
                        background
                        :pager-count="5"
                        @size-change="handleSizeChange"
                        @current-change="handleRightCurrentChange"
                        :current-page.sync="form.pageNumber"
                        :page-size="form.pageSize"
                        layout="sizes,total, prev, pager, next, jumper"
                        :total="formPageTabletotal"
                        :page-sizes="[10, 20, 50, 100]"
                ></el-pagination>


            </div>

        </div>

        <el-card class="contextmenu" ref="card" v-show="menuVisible">
            <div class="edit" @click="">
                <i class="el-icon-edit"></i>&nbsp;&nbsp;{{this.i18n.t('edit')}}
            </div>
            <div class="delete" @click="">
                <i class="el-icon-remove-outline"></i>&nbsp;&nbsp;{{this.i18n.t('delete')}}
            </div>
        </el-card>

        <deleteDialog ref='deleteDialog' :applyType="applyType" :persionIds="persionIds" :editTableRow='editTableRow' :deleteFlag.sync='deleteFlag' v-if='deleteFlag'></deleteDialog>
        <editOrAdd ref='editOrAdd' :handleEditOrAddType="handleEditOrAddType" :editTableRow='editTableRow'
                   :editOrAddFlag.sync='editOrAddFlag' v-if='editOrAddFlag'></editOrAdd>
        <importDialog ref='importDialog' :editTableRow='editTableRow' :importFlag.sync='importFlag'
                      v-if='importFlag'></importDialog>
        <synchronous ref='importDialog' :editTableRow='editTableRow' :syncFlag.sync='syncFlag'
                     v-if='syncFlag'></synchronous>
        <distributeList ref='distributeListDialog' :editTableRow='noDepartmentPersonnel' :distributeFlag.sync='distributeFlag'
                        v-if='distributeFlag'></distributeList>
        <addOrg ref='addOrgDialog' :handleType="handleType" :leftTreeAddData='leftTreeAddData'
                :addOrgFlag.sync='addOrgFlag' v-if='addOrgFlag'></addOrg>
        <editOrg ref='editOrgDialog' :editOrgFlag="editOrgFlag" :orgRowData='orgRowData'
                 :editOrgFlag.sync='editOrgFlag' v-if='editOrgFlag'></editOrg>
        <updateUserOrg ref='updateUserOrg' :editTableRow='editTableRow' @getdepartmenttree="getdepartmenttree"
                   @onSearch="onSearch" :updateUserOrg.sync='updateUserOrg' v-if='updateUserOrg'></updateUserOrg>
    </div>
</template>

<script>
    import "@/assets/common/css/treeStyle.css";
    import {sexList} from '@/assets/common/js/utils/deviceConfig.js'
    import {fileShowSaveDialog, fileShowOpenDialog} from '@/api/sbgl'//引入接口
    import {filterTreeData, traverseDep, getParentsByName} from './utils.js'
    import {devicemodelgetlist, getList} from "@/api/jxgl";
    import {deleteDocument} from "@/api/document";
    import {
        getdepartmenttree,
        departmentinfoDeletedepartment,
        exportpersoninfotoexcel,
        personnelinfoDelete,
        personnelinfoGetlist,
        fileFiletobase64,
        personnelinfoBatchdelete,
        personnelinfoCleanallperson,
        fileImageconverttobase64
    } from "@/api/pcmj/zzxx";
    //  删除弹窗
    import deleteDialog from './deleteDialog.vue';
    // 引入新增修改弹框
    import editOrAdd from './editOrAdd.vue'
    // 导入弹框
    import importDialog from './import.vue'
    // 同步名单弹窗
    import synchronous from './synchronous.vue'
    // 下发名单弹窗
    import distributeList from './distributeList.vue'
    // 修改人员组织弹框
    import updateUserOrg from './updateUserOrg.vue'
    // 添加组织弹窗
    import addOrg from './org/addOrg.vue'
    // 修改组织弹窗
    import editOrg from './org/editOrg.vue'

    export default {
        name: "sbsj_index",
        components: {
            editOrAdd,
            deleteDialog,
            importDialog,
            synchronous,
            addOrg,
            editOrg,
            distributeList,
            updateUserOrg
        },
        props: {},
        data() {
            var validateIdCard = (rule, value, callback) => {
                if(this.searchType==2){
                    if (value == '' || value == undefined) {
                        // 请输入证件号码
                        callback(new Error(this.i18n.t('Please enter your ID number')));
                    } else if (!this.$rules.idCard.reg.test(value)) {
                        callback(new Error(this.i18n.t('Please enter your ID number') + this.$rules.idCard.min + '~' + this.$rules.idCard.max + ' ' + this.i18n.t('bits')));
                    } else {
                        callback();
                    }
                }

            };
            var validateName = (rule, value, callback) => {
                console.log(value);
                if (value == '' || value == undefined) {
                    // 请输入姓名
                    callback(new Error(this.i18n.t('Please enter your name')));
                } else if (!this.$rules.name.reg.test(value)) {
                    callback(new Error(this.$rules.name.min + '~' + this.$rules.name.max + ' ' + this.i18n.t('bits')));
                } else {
                    callback();
                }

            };
            return {
                orginfoLoading:false,
                leftTreeDisplay:false,
                importLoading:false,
                orgId:null,
                formPageTabletotal:0,
                sexListArr:[],
                menuVisible: false,
                defaultJson: [
                  {
                    id: -100,
                    name: this.i18n.t('default'),
                    children: []
                  }
                ],
                noDepartmentPersonnel: [
                    {
                        id: -100,
                        name: this.i18n.t('default'),
                        children: []
                    }
                ],
                rules: {
                    name: [
                        {validator: validateName, required: true, trigger: 'blur'}
                    ],
                    idCard: [
                        {validator: validateIdCard, required: true, trigger: 'blur'}
                    ],
                },
                searchForm: {},
                searchKeyWords: "",
                searchType: -1,
                listData: [],
                deprops: { // 默认配置
                    value: 'id', // treeId 为节点id，唯一值
                    label: 'name',
                    children: 'children',
                },
                defaultExpand: [], // 默认展开节点
                defaultChecked: [], // 默认选中节点，用于回显
                defaultProps: {
                    children: 'children',
                    label: 'name',
                    disabled: function (data, node) {
                        // console.log(132,data,data.sex, node);
                        return true
                        // 禁用复选框选项
                        // if (data.sex!==undefined) {
                        //     return true
                        // }else{
                        //     return false
                        // }
                    }
                },
                expaAndList: [],
                input: '',
                regDate: '',
                pickerOptions: {
                    shortcuts: [{
                        // 最近一周
                        text: this.i18n.t('Last week'),
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        // 最近一个月
                        text: this.i18n.t('Last month'),
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        // 最近三个月
                        text: this.i18n.t('Last three months'),
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                form: {
                    pageNumber: 1,
                    pageSize: 10,
                    dateTimeStart: '',//开始时间
                    dateTimeEnd: '',//结束时间
                    searchKeyWords: '',//模糊查询关键字（工号，姓名，身份证号）
                    departmentIds: [],//模糊查询关键字（工号，姓名，身份证号）
                    personelId: null,
                    name: null,
                    idCard: null
                },
                queryText:null,
                selectRow: [],
                editTableRow: null,
                leftTreeAddData: null,
                deleteFlag: false,
                editOrAddFlag: false,
                importFlag: false,
                syncFlag: false,
                distributeFlag: false,
                addOrgFlag: false,
                editOrgFlag: false,
                handleType: '',
                handleEditOrAddType: '',
                orgInfo: [],
                orgRowData: [],
                leftTreeLoading: false,
                loadingText: this.i18n.t('Loading'),
                loadingObj: null,
                updateUserOrg: false,
                persionIds:[],
                applyType:0,
                input3: '',
                select: '',
                tree:[],
                leftTreeHeight:0
            };
        },
        computed: {},
        watch: {
          leftTreeDisplay:{
            handler (newVal,oldVal) {
              if (newVal){
                this.setLeftTreeHeight()
              }

            },
            deep: true // 深度监听
          },
        },
        created(){
            // 获取组织部门权限树
            this.getdepartmenttree();
        },
      mounted() {
            var _this=this
            this.sexListArr=sexList

            this.onSearch();

            window.addEventListener("resize",this.setLeftTreeHeight)

            // window.onresize = function () {//用于使表格高度自适应的方法
            //   _this.setLeftTreeHeight()//设置左侧组织树高度
            // }
        },
      beforeDestroy(){
        window.removeEventListener('resize', this.setLeftTreeHeight)
      },
        methods: {
            packAll(){
                console.log(this.$refs.orgTree.store);
                this.$refs.orgTree.store.root.expanded = false
            },
            toTree(){
                this.$router.push({ path: '/treeTest' })
            },
            // 获取组织下的人数
            getOrgPersionCount(item){
                console.log(item);
                var count=0
                if (Array.isArray(item)){
                    item.map(res=>{
                        if (res.sex!==undefined){
                            count++
                        }
                    })
                }

                return count
            },
          setLeftTreeHeight(){
            // 计算左侧组织树的高度
            this.leftTreeHeight=document.getElementById('leftTreeView').clientHeight-35
            console.log('leftTreeView高度',this.leftTreeHeight);
          },
            handleRightCurrentChange(val) {
                this.form.pageNumber = val;
                this.onSearch()
            },
            handleSizeChange(val) {
                this.form.pageSize = val
                // this.filterImgToBase64()
                console.log(`每页 ${val} 条`);
                this.onSearch()
            },
            handleBottomCommand(command) {
                switch (command) {
                    case 'import':
                        this.importManage()
                        console.log('导入')
                        break;
                    case 'modifyOrg':
                        this.modifyOrg()
                        break;
                    case 'batchDelete':
                        this.batchDelete()
                        console.log('批量删除')
                        break;
                    case 'emptyingPersonnel':
                        this.emptyingPersonnel()
                        console.log('清空人员')
                        break;
                    case 'exportFile':
                        this.exportpersoninfotoexcel()
                        console.log('导出')
                        break;
                }
            },
            modifyOrg() {
                this.updateUserOrg = true
            },
            resetSearchStr() {
                this.form.personelId = null
                this.form.name = null
                this.form.idCard = null
            },
            searchTypeChange() {
                this.resetSearchStr()
            },
            resetSearch() {
                this.searchType = -1
                this.queryText=null
                this.jobNumber=null
                this.regDate = ""
                this.form.searchKeyWords = null
                this.form.pageNumber = 1
                // 重新加载表格
                this.onSearch()
            },
            fileChange(e) {
                if (this.isElectron) {
                    console.log(e.target.files[0].path);
                    console.log(e.target.files);
                } else {
                    this.W.$tips("warning", this.i18n.t("Please operate on the desktop!"));
                }
            },
            // 更新左侧组织树和右侧表格数据
            updatePageData() {
                // 重新加载组织部门权限树
                this.getdepartmenttree();
                // 重新加载表格
                this.onSearch()
            },
            // 重置保存按钮的loading状态
            resetLoading(){
                this.saveLoading=false
            },
            async applyToDeviceFn(deviceIdList,isDelPersion){
                console.log('父页面收到的设备列表',deviceIdList);

                if(this.applyType==0){
                    // 单个删除人员、批量删除人员
                    var selectPresionIdList = []
                    if(this.selectRow.length){
                        this.selectRow.forEach(item => {
                            selectPresionIdList.push(item.id)
                        })
                    }else{
                        selectPresionIdList = [this.editTableRow.id]
                    }


                    var params={
                        onlyApplyDevice:false,
                        applyDeviceCodes:deviceIdList,
                        // personIds:this.editTableRow?[this.editTableRow.id]:this.persionIds
                        personIds:selectPresionIdList
                    }
                    // 单个删除人员、批量删除人员
                    this.personnelinfoBatchdelete(params)
                }else if(this.applyType==1){
                    // 清空人员
                    this.personnelinfoCleanallperson(deviceIdList)
                }else if(this.applyType==3){
                    // 删除左侧组织
                    let res = await departmentinfoDeletedepartment({
                        departmentId:this.orgId,
                        deleteIncludePerson:isDelPersion,
                        applyDeviceCodes:deviceIdList,
                    });
                    if (res.code == 200) {
                        // 删除成功
                        this.W.$tips("success", this.i18n.t('Successfully deleted'));
                        // 更新页面数据
                        this.updatePageData()
                    }
                }


            },

            // 清空人员
            personnelinfoCleanallperson(params){
                personnelinfoCleanallperson(params).then(res => {
                    if (res.code == 200) {
                        this.W.$tips("success", this.i18n.t('Successfully deleted'));
                        // 更新页面数据
                        this.updatePageData()
                    }
                }).catch().finally(()=>{
                    this.saveLoading=false
                })
            },
            // 删除人员
            personnelinfoBatchdelete(params){
                personnelinfoBatchdelete(params).then(res => {
                    if (res.code == 200) {
                        this.W.$tips("success", this.i18n.t('Successfully deleted'));
                        // 更新页面数据
                        this.updatePageData()
                    }
                }).catch().finally(()=>{
                    this.saveLoading=false
                })
            },

            // 清空人员
            emptyingPersonnel(){
                this.applyType=1
                this.deleteFlag=true
            },
            // 单个删除人员
            deletePersonnel(row){
               this.applyType=0
               this.editTableRow=row
               this.deleteFlag=true
            },
            // 批量删除人员
            batchDelete() {
                if (!this.selectRow.length) {
                    // 请在表格内勾选要删除的数据
                    this.W.$tips("warning", this.i18n.t('Please check the data to be deleted in the table'));
                } else {
                    // 显示确认弹窗
                    var idItem = []
                    this.selectRow.forEach(item => {
                        idItem.push(item.id)
                    })
                    console.log('删除的ID', idItem);
                    this.applyType=0
                    this.persionIds = idItem
                    this.deleteFlag = true
                }
            },
            /**
             * @param arr:{data} --勾选的数据
             * @return: not
             * 表格勾选回调
             */
            handleTableSelectionChange(selection) {
                console.log(selection);
                this.selectRow = selection;
            },
            handleRightSelectionChange(selection) {
                this.rightSelection = selection
            },
            beforeHandleCommand(row, command) {
                return {
                    'row': row || {},
                    'command': command
                }
            },
            // 左侧权限树增加人员
            treeAddPerson(row) {
            },
            // 刷新组织部门权限树
            refreshTree() {
                // this.orgInfo=[]
                this.getdepartmenttree()
            },
            // 表格删除回调
            delTableData(row) {
                console.log(row);
                // 确定要删除？
                this.W.$myConfirm('warning', this.i18n.t('Are you sure you want to delete XXX?') + ' <strong style="color: red;">' + row.name + '</strong> ？')
                    .then(async () => {
                        let res = await personnelinfoDelete({id: row.id});
                        if (res.code == 200) {
                            // 删除成功
                            this.W.$tips("success", this.i18n.t('Successfully deleted'));
                            // 更新页面数据
                            this.updatePageData()
                        }
                    })
                    .catch(() => {
                    });
            },
            //左侧权限树删除
            async remove(node, data) {
                console.log(357, node, data);
                this.editTableRow=data
                // debugger
                if(data.sex !== undefined){
                    this.orgId=null
                    this.applyType=0

                    // // 确定要删除？如果当前组织内有绑定人员，点击确定后删除该组织，人员自动归类至 默认 中！
                    // this.W.$myConfirm('warning', this.i18n.t('Are you sure you want to delete XXX?') + ' <strong style="color: red;">' + data.name + '</strong> ？<br>' + this.i18n.t('Automatic personnel classification'))
                    //     .then(async () => {
                    //
                    //         // 删除人员
                    //         let res = await personnelinfoDelete({id: data.id});
                    //         if (res.code == 200) {
                    //             // 删除成功
                    //             this.W.$tips("success", this.i18n.t('Successfully deleted'));
                    //             // 更新页面数据
                    //             this.updatePageData()
                    //         }
                    //     })
                    //     .catch(() => {
                    //     });


                }else{
                    this.orgId=data.id
                    // 删除组织
                    this.applyType=3
                }
                // 显示是否应用到设备弹窗
                this.deleteFlag=true




            },
            editOrgInfo(node, data) {
                console.log(data);
                this.orgRowData = data
                this.editOrgFlag = true
            },
            // 选择保存路径
            fileShowSaveDialog(params, row) {
                fileShowSaveDialog(params).then((res) => {
                    if (res.code === 200) {
                        this.sbglDevStartdatabackup(row.deviceCode, res.data)
                    }
                }).catch().finally(() => {
                })
            },
            exportpersoninfotoexcel() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        this.importLoading=true
                        var params = this.getFormData()
                        // this.leftTreeLoading = true
                        this.$nextTick(async () => {
                            exportpersoninfotoexcel(params).then((res) => {


                                let blob = new Blob([res], {type: 'application/zip'})
                                let url = window.URL.createObjectURL(blob)
                                const link = document.createElement('a') // 创建a标签
                                link.href = url
                                link.download = this.i18n.t('Personnel List') + new Date().toLocaleString() // 重命名文件
                                link.click()
                                URL.revokeObjectURL(url) // 释放内存

                                // 导出成功
                                this.W.$tips('success',  this.i18n.t('Export successful'));

                                // this.G.exportFile(res, this.i18n.t('Personnel List') + new Date().toLocaleString())
                                // if (res.code === 200) {
                                // }
                            }).catch().finally(() => {
                                this.importLoading=false
                            })
                        });
                    }
                })

            },
            /**
             * @description  获取部门人员树
             * @param :
             **/
            getdepartmenttree() {
              this.noDepartmentPersonnel=[
                {
                  id: -100,
                  name: this.i18n.t('default'),
                  children: []
                }
              ]
              this.leftTreeDisplay=false
                this.orginfoLoading = true
                this.leftTreeLoading = true
                this.$nextTick(async () => {
                    getdepartmenttree({IncludePersonInfo: true}).then((res) => {
                        if (res.code === 200) {
                          if(res.data.rootDepartments.length){
                            res.data.rootDepartments = filterTreeData(res.data.rootDepartments)
                            console.log('待合并的数据',res.data.rootDepartments);
                            res.data.rootDepartments.map(item=>{
                              this.noDepartmentPersonnel.push(item)
                            })
                            this.noDepartmentPersonnel.concat(res.data.rootDepartments)
                            console.log('处理后的数据',this.noDepartmentPersonnel);
                          }
                          this.$set(this.noDepartmentPersonnel[0],'children',res.data.personnelOfWithOutDepartment)
                          console.log('最终的组织树数据',this.noDepartmentPersonnel);
                            console.log('组织树数据',this.noDepartmentPersonnel);

                            setTimeout(()=>{
                              this.leftTreeDisplay=true
                            },300)
                        }
                    }).catch().finally(() => {
                        setTimeout(() => {
                            this.leftTreeLoading = false
                            this.orginfoLoading = false
                        }, 500)
                    })

                });
            },
            // 添加组织
            addOrg(data) {
                console.log('当前节点data', data);
                this.handleType = 'add'
                this.leftTreeAddData = data
                this.addOrgFlag = true
            },
            // 下发名单
            distributeList() {
                this.distributeFlag = true
            },
            synchronous() {
                this.syncFlag = true
            },
            importManage() {
                // if (!this.isElectron){
                //     this.W.$tips("warning", "请在桌面端操作!");
                //     return
                // }
                this.importFlag = true
            },
            handleNodeClick(data, checked, node) {
                console.log(data);
                this.expaAndList = data.treeId
            },
            testFun() {
                this.W.$tips('warning', '未实现');
            },
            // 将本地文件转成Base64
            async fileFiletobase64(filePath) {
                let res = await fileFiletobase64({filePath: filePath});
                return res
            },
            // 获取人员表格数据
            personnelinfoGetlist(params) {
                console.log(123);
                personnelinfoGetlist(params).then(async res => {
                    console.log(345);
                    if (res.code == 200) {
                        if (res.data.values) {
                            var data = JSON.parse(JSON.stringify(res.data.values))
                            for (var i = 0; i < data.length; i++) {
                                if (data[i].biodataInfos && 'face' in data[i].biodataInfos&&data[i].biodataInfos.face.length) {
                                    var  suffix= data[i].biodataInfos.face[0].fileInfo.substring(data[i].biodataInfos.face[0].fileInfo.lastIndexOf('.') + 1)

                                    // 转base64显示
                                    await fileImageconverttobase64(data[i].biodataInfos.face[0].fileInfo).then((res) => {
                                        data[i].biodataInfos.face[0].showBase64Pic = res
                                    })
                                    // if(suffix=='jp2'){
                                    //     // 转base64显示
                                    //     await fileImageconverttobase64(data[i].biodataInfos.face[0].fileInfo).then((res) => {
                                    //         data[i].biodataInfos.face[0].showBase64Pic = res
                                    //     })
                                    // }else{
                                    //     await this.fileFiletobase64(data[i].biodataInfos.face[0].fileInfo).then(res => {
                                    //         data[i].biodataInfos.face[0].showBase64Pic = res
                                    //     })
                                    // }
                                }
                            }
                            this.listData=data
                            console.log(922,this.listData);
                        } else {
                            this.listData=[]
                        }
                        this.formPageTabletotal=res.data.totalCount
                    }
                })
            },
            getFormData() {
                var params = JSON.parse(JSON.stringify(this.form))
                params = {
                    dateTimeStart: this.form.dateTimeStart || null,
                    dateTimeEnd: this.form.dateTimeEnd || null,
                    pageNumber: this.form.pageNumber,
                    pageSize: this.form.pageSize,
                    name: null,
                    personelId: null,
                    idCard: null,
                    jobNumber: null,
                    searchKeyWords: null,
                }
                if (this.searchType == -1) {
                    params.searchKeyWords = this.queryText
                }
                if (this.searchType == 0) {
                    params.name = this.form.name
                }
                if (this.searchType == 1) {
                    params.personelId = this.form.personelId
                }
                if (this.searchType == 2) {
                    params.idCard = this.form.idCard
                }
                if (this.regDate) {
                    var formatStr = "yyyy-MM-dd"
                    params.dateTimeStart = new Date(this.regDate[0]).format(formatStr) + ' 00:00:00'
                    params.dateTimeEnd = new Date(this.regDate[1]).format(formatStr) + ' 23:59:59'
                }
                return params
            },
            onSearch() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        var params = this.getFormData()
                        if (this.searchType==-1){
                            params.name=null
                            params.idCard=null
                            params.jobNumber=null
                        }
                        // 姓名
                        if (this.searchType==0){
                            params.name=this.queryText
                            params.idCard=null
                        }
                        // 证件号码
                        if (this.searchType==2){
                            params.name=null
                            params.idCard=this.queryText
                        }
                        // 编号（工号）
                        if (this.searchType==3){
                            params.name=null
                            params.idCard=null
                            params.jobNumber=this.queryText
                        }
                        console.log(957,params);
                        this.personnelinfoGetlist(params)
                    }
                })

            },
            /**
             * @description  添加表格
             * @param {row}: Object 点击项数据
             **/
            addTableData() {
                this.editTableRow = null;
                // if (rowData) {
                //     this.editTableRow = rowData;
                // } else {
                //     this.editTableRow = {}
                // }
                this.handleEditOrAddType = 'add';
                console.log('添加',this.editTableRow);
                this.editOrAddFlag = true;
            },
            /**
             * @param arr:{data} --当前行数据
             * @return: not
             * 表格查看的回调
             */
            handelDetail(row) {
                console.log(row);
                this.editOrAddFlag = true;
                this.handleEditOrAddType = 'view';
                this.editTableRow = row;
            },
            //  表格修改回调
            handlePersonEdit(row) {
                console.log(525, row);
                this.editOrAddFlag = true;
                this.handleEditOrAddType = 'edit';
                this.editTableRow = row;
            },
            //  左侧组织树修改回调
            handleTreePersonEdit(node, data) {
                console.log('当前行数据', node, data);
                // 修改人员
                if ('sex' in data) {
                    this.handlePersonEdit(data)
                    // if ('face' in data.biodataInfos && data.biodataInfos.face.length) {
                    //     this.fileFiletobase64(data.biodataInfos.face[0].fileInfo).then(res => {
                    //         data.imagePath = res
                    //         this.handlePersonEdit(data)
                    //     })
                    // } else {
                    //     data.imagePath = '-'
                    //     this.handlePersonEdit(data)
                    // }
                }
                // 修改组织
                else {
                    console.log('修改组织');
                    this.orgRowData = data
                    this.editOrgFlag = true
                }
            },
        }
    };
</script>

<style lang="scss" scoped>
    #customTree {
        /*border: 1px solid red;*/
        /*height: calc(100% - 90px);*/
        overflow-y: scroll !important;
        .userIcon,.orgIcon{
            color:#0666d2;
            &.female{
                color:#ff7700;
            }
        }
        .orgIcon{
            margin-right: 5px;
        }
        .treeTool{

            .treeToolIcon{
                color: #409eff;
                /*font-weight: bold;*/
                margin-left: 8px;
                vertical-align: middle;
            }
        }
    }

    .treeTopIcon {
        i {
            color: #2378d7;
            margin-left: 10px;
            /*font-weight: bold;*/
            cursor: pointer;
            font-size: 16px;

            &:hover {
                opacity: 0.7;
            }

            &:active {
                opacity: 0.9;
            }
        }
    }

    .noDepartmentName {
        vertical-align: middle;
        display: inline-block;
        width: 150px;
        /*border: 1px solid red;*/
    }

    .noDepartmentName, .departmentName {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap
    }

    .container {
        display: flex;
        /*justify-content: space-between;*/
        align-items: stretch;
        border: 0px solid green;

        .leftNav {
          border-bottom-left-radius: 4px;
          border-bottom-right-radius: 4px;
            width: 300px;
            display: inline-block;
            border: 0px solid red;
          overflow: hidden;
        }

        .rightTable {
            display: inline-block;
            border: 0px solid red;
            width: calc(100% - 320px);
            box-sizing: border-box;
            margin-left: 16px;
            /*margin-right: 16px;*/
        }
    }
</style>
<style>
    .el-checkbox__input.is-disabled {
        display: none !important;
    }

    .el-tree {
        overflow: visible !important;
        /*display: inline-block;*/
    }

    .el-tree {
        width: 100%;
        overflow: scroll;
    }

    .el-divider--horizontal {
        margin: 2px 0 !important;
    }

    /*/deep/ .el-tree>.el-tree-node {*/
    /*display: inline-block;*/
    /*min-width: 100%;*/
    /*}*/
    .contextmenu {
        /*width: 150px;*/
        position: absolute;
        z-index: 1000;
    }
    #queryType .el-select .el-input {
        width: 130px;
    }
    /*.input-with-select .el-input-group__prepend {*/
    /*    background-color: #fff;*/
    /*}*/
    /*.vl-tree-node.focusable:hover .orgInfoTool{*/
        /*display: inline-block;*/
    /*}*/
    /*.orgInfoTool:nth-child(1){*/
        /*margin-right: 10px;*/
    /*}*/
    /*.orgInfoTool{*/
        /*!*display: none;*!*/
        /*vertical-align: middle;*/
        /*color: #0666d2;*/
        /*cursor: pointer;*/
    /*}*/
    /*!*.vl-tree-node.focusable:nth-child(5){*!*/
        /*!*background-color: #f4f4f8;*!*/
    /*!*}*!*/
    /*.vl-tree-node.focusable:hover{*/
        /*background-color: #f4f4f8;*/
    /*}*/
    #leftTreeView{
      border: 0px solid red !important;
      padding: 10px 0 10px 10px;
      box-sizing: border-box;
    }
    .leftNav .el-card{
      border-bottom-left-radius: 0px;
      border-bottom-right-radius: 0px;
    }
</style>
